package me.raih.controller.user;

import me.raih.pojo.po.User;
import me.raih.pojo.vo.ResultInfo;
import me.raih.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @Author Raih
 * @Time 2020/12/14 16:29
 *
 * 用户登录控制
 */
@Controller
@RequestMapping(value = "/user")
public class UserLoginController {


    @Autowired
    ResultInfo resultInfo;

    @Autowired
    UserService userService;

    /**
     * 前往登录页面
     * @return
     */
    @RequestMapping(value = {"/login","/login.html"})
    public String toLogin(){

        //System.out.println("来到了这里！");

        return "user/login";
    }

    @RequestMapping(value = "/userLoginCheck",method = RequestMethod.PUT)
    @ResponseBody
    public ResultInfo userLoginCheck(HttpSession session, @RequestParam("username")String username,@RequestParam("password")String password,@RequestParam("checkCode") String checkCode){

        //获取session中的验证码
        Object verify_codegen = session.getAttribute("VERIFY_CODEGEN");
        if(verify_codegen != null ){
            //不相等就是 验证码错误  记住要忽视大小写
            if(!verify_codegen.toString().equalsIgnoreCase(checkCode)){
                resultInfo.setMessage("验证码错误，请重新输入");
                resultInfo.setFlag(false);
            }else {
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                User u = userService.findUserByUser(user);
                if(u != null){
                    session.setAttribute("USER_LOGIN_SESSION_FLAG",u);
                    resultInfo.setFlag(true);
                }else {
                    resultInfo.setFlag(false);
                    resultInfo.setMessage("用户名或密码错误，请重试");
                }
            }
        }

        return resultInfo;
    }

    //退出登录
    @RequestMapping(value = "/logOut",method = RequestMethod.DELETE)
    @ResponseBody
    public String logOut(HttpSession session){
        //删除session
        session.removeAttribute("USER_LOGIN_SESSION_FLAG");
        //session.invalidate();

        return "退出成功";
    }



}
